package com.jhh.pay.driver.service.impl;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.Random;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.health.model.HealthService;
import com.jhh.pay.driver.service.DiscoveryService;

@Component
public class DefaultDiscoveryService implements DiscoveryService {
	
	private Random random = new Random();
	
	@Value("${spring.cloud.consul.host}")
	private String host;
	
	@Value("${spring.cloud.consul.port}")
	private int port;
	
	private ConsulClient client;
	
	public DefaultDiscoveryService(String host, int port) {
		this.host = host;
		this.port = port;
		init();
	}
	
	public DefaultDiscoveryService() {
		this("localhost", 8500);
	}
	
	public DefaultDiscoveryService(String host) {
		this(host, 8500);
	}
	
	@PostConstruct
	public void init() {
		client = new ConsulClient(host,port);
	}
	
	@Override
	public InetSocketAddress getServiceAddress(String serviceName) {
		Response<List<HealthService>> healthyServices = client.getHealthServices(serviceName, true, QueryParams.DEFAULT);
		List<HealthService> healthServices = healthyServices.getValue();
		if(!healthServices.isEmpty()) {
			HealthService healthService = healthServices.get(random.nextInt(healthServices.size()));
			return new InetSocketAddress(healthService.getService().getAddress(), healthService.getService().getPort());
		}
		return null;
	}

}
